<template>
  <div class="page-tab-wrap">
    <div class="page-tab">
      <div
        :class="[
          'page-tab-arrow-left page-tab-left',
          noActiveLeft ? 'noActive' : ''
        ]"
        @click="scrollTab('left')"
      >
        <span class="ivu-icon ivu-icon-ios-arrow-back"></span>
      </div>
      <div class="tab-close page-tab-right" @click="closeTab(pageTabList)">×</div>
      <div
        :class="[
          'page-tab-arrow-right page-tab-right',
          noActiveRight ? 'noActive' : ''
        ]"
        @click="scrollTab('right');"
      >
        <span class="ivu-icon ivu-icon-ios-arrow-forward"></span>
      </div>
      <ul ref="pageTab" class="page-tab-list">
        <li
          :class="['page-tab-item', item.active ? 'active' : '']"
          v-for="item in pageTabList"
          :key="item.tabName"
          @click="goToPage(item.tabName,item)"
        >
          <span>{{ item.tabText }}</span>
          <span class="table-item-close" @click.stop="closeTab(item)">×</span>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { tabManager } from "@/libs/tool/util";
export default {
  name: "pageTab",
  props: {
    closeToPage: {
      type: String,
      default: "userMessage"
    }
  },
  created() {},
  destroyed() {},
  data() {
    return {
      currentRouterName: "",
      noActiveLeft: true,
      noActiveRight: false,
      pageTabList: [],
      currentScroll: 0,
      offsetWidth: 0,
      scrollWidth: 0,
      pageTab: ""
    };
  },
  watch: {
    $route: {
      handler(router) {
        // 获取localname
        this.currentRouterName = router.name; // 路由name

        let list = tabManager.getRouter();
        const ele = tabManager.getRouterByName(list, router.name);
        if (ele) {
          list = tabManager.setActive(list, ele.name);
        } else {
          list = tabManager.add(list, router);
        }
        //暂时隐藏用户信息管理页面的内容以及tab按钮
        list = list.filter(item => {
          return item.tabText !== "用户信息管理";
        });
        this.pageTabList = list;
        tabManager.saveData(list);
        this.renderArrowStatus();
      },
      immediate: true
    },
    pageTabList(val) {
      let cachedViews = val.map(v => {
        return v.name;
      });
      this.$store.dispatch("tagView/updateCachedView", cachedViews);
    }
  },
  mounted() {
    this.pageTab = this.$refs["pageTab"];
    this.offsetWidth = this.pageTab.offsetWidth;
    this.scrollWidth = this.pageTab.scrollWidth;
  },
  methods: {
    // 跳转目标页面
    goToPage(name, local) {
      if (local && local.bufferPath) {
        // 取缓存的query get url
        this.$router.push({
          path: local.bufferPath
        });
      } else {
        this.$router.push({
          name: name
        });
      }
    },
    // 关闭页签
    closeTab(items) {
      if (
        Object.prototype.toString.call(items).toLocaleLowerCase() ===
        "[object array]"
      ) {
        // 传入参数
        tabManager.clear();
        this.pageTabList = [];
        this.goToPage(this.closeToPage);
      } else {
        let name = items.name;
        let routers = tabManager.getRouter();
        routers = tabManager.removeRouterByName(routers, name); // 删除当前

        const tab = routers[routers.length - 1];

        tabManager.saveData(routers);
        if (name === this.currentRouterName) {
          if (tab) {
            this.goToPage(tab.name);
          } else {
            this.goToPage(this.closeToPage);
          }
        }
        this.pageTabList = routers;
        this.renderArrowStatus();
      }
    },
    // 获取scrollWidth 设置箭头状态
    renderArrowStatus() {
      this.scrollWidth = this.pageTab.scrollWidth;
      this.noActiveLeft = !(this.currentScroll > 0);
      this.noActiveRight =
        !(this.currentScroll < this.scrollWidth) ||
        this.offsetWidth === this.scrollWidth;
    },

    // 控制滚动
    scrollTab(direction) {
      if (this.scrollWidth === this.offsetWidth) {
        return false;
      }
      let scrollVal = 0;
      switch (direction) {
        case "right":
          scrollVal =
            this.offsetWidth + this.currentScroll <= this.scrollWidth
              ? this.currentScroll + this.offsetWidth
              : this.scrollWidth;
          break;
        case "left":
          scrollVal =
            this.currentScroll - this.offsetWidth > 0
              ? this.currentScroll - this.offsetWidth
              : 0;
      }
      this.scrollLeft(this.pageTab, this.currentScroll, scrollVal, 1000);
      this.currentScroll = scrollVal;
      this.renderArrowStatus();
    },
    scrollLeft(el, from = 0, to, duration = 500, endCallback) {
      const difference = Math.abs(from - to); // 滚动距离
      const step = Math.ceil((difference / duration) * 50); // 步长
      function _scroll(start, end, step) {
        if (start === end) {
          endCallback && endCallback();
          return;
        }
        // 每次绘制动画时更新起始距离
        let d = start + step > end ? end : start + step;
        if (start > end) {
          d = start - step < end ? end : start - step;
        }
        if (el === window) {
          window.scrollTo(d, d);
        } else {
          el.scrollLeft = d;
        }
        // requestAnimationFrame实现最优性能动画绘制
        window.requestAnimationFrame(() => scroll(d, end, step));
      }
      _scroll(from, to, step);
    }
  }
};
</script>
<style lang="scss" scoped>
.page-tab-wrap {
  padding-bottom: 5px;
}

.page-tab {
  font-size: 14px;
  color: #666;
  overflow: hidden;
}

.page-tab-left {
  float: left;
}

.page-tab-right {
  float: right;
}

.page-tab-left {
}

.page-tab-list {
  overflow: hidden;
  height: 30px;
  white-space: nowrap;
  word-wrap: normal;
}
.page-tab-item {
  display: inline;
  cursor: pointer;
  margin-left: 5px;
  border-radius: 2px;
  border: 1px solid #efefef;
  background-color: #fff;
  padding: 5px 7px;
  position: relative;
  top: 4px;
  &.active {
    background-color: #0893fd;
    border-color: #0893fd;
    color: #fff;
  }
  &:first-child {
    margin-left: 0;
  }
}
.table-item-close {
  font-size: 14px;
  &:hover {
    color: #ca4341;
  }
}
.tab-close {
  font-size: 20px;
  margin-left: 10px;
  cursor: pointer;
  &:hover {
    color: #ca4341;
  }
}
.page-tab-arrow-right,
.page-tab-arrow-left {
  cursor: pointer;
  position: relative;
  top: 4px;
}

.page-tab-arrow-right span,
.page-tab-arrow-left span {
  font-size: 18px;
  color: #7d7d7d;
}

.page-tab-arrow-right,
.page-tab-arrow-left {
  &.noActive {
    cursor: default;
    span {
      color: #d8d8d8;
    }
  }
}
.page-tab-arrow-left {
  margin-right: 5px;
}
.page-tab-arrow-right {
  margin-left: 5px;
}
</style>
